package com.cortex.carambola.fetch;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.cortex.carambola.utilities.MessagesLog;


public class FetchVideos {

	private OnStateChanged onStateChanged;
	private int videosAmount;
	private List<Video> videos;

	private final static int TIME_OUT_CONNECTION = 5000;
	StartImagesThread startImagesThread;


	public FetchVideos(){
		videos = new ArrayList<Video>();
	}
	public void startFetching(String url,int imagesNumberToFetching){
		if(isFetching() || (videosAmount == videos.size() && videosAmount != 0)){
			return;
		}

		startImagesThread = new StartImagesThread();
		startImagesThread.execute(url);
	}
	public void cancelFetching(){
		if(startImagesThread !=  null){
			startImagesThread.cancel(true);
		}
	}
	public boolean isFetching() {
		return startImagesThread == null?false:startImagesThread.isRunning();
	}
	public void setOnStateChanged(OnStateChanged onStateChanged) {
		this.onStateChanged = onStateChanged;
	}
	public int getAmountVideos(){
		return videosAmount;
	}
	private class StartImagesThread extends AsyncTask<String, Video, List<Video>>{

		private Document doc;
		private boolean isRunning = false;
		private String baseUrl;



		@Override
		protected List<Video> doInBackground(String... params) {

			try {
				//Connect to the website and get the html
				connectToUrl(params[0]);
				findAllVideos();				

			} catch (IOException e) {
				String message = e.getMessage();
				Log.d(MessagesLog.APPLICATION_EXCEPTION,"" + message);
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return videos;
		}
		@Override
		protected void onPreExecute() {
			isRunning = true;
			if(onStateChanged != null){
				onStateChanged.timeLoadStarted();
			}
		}
		@Override
		protected void onProgressUpdate(Video... values) {
			if(onStateChanged != null){
				onStateChanged.downloadedData(values[0], videos.size(), videosAmount);
			}
		}
		@Override
		protected void onPostExecute(List<Video> images) {
			isRunning = false;
			if(onStateChanged != null){
				onStateChanged.timeLoadFinished(images);
			}
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
			if(onStateChanged != null){
				onStateChanged.timeLoadCanceled("summary canceled");
			}
		}
		private void connectToUrl(String url) throws IOException{
			doc = Jsoup.connect(url).timeout(TIME_OUT_CONNECTION).get();
			String[] arr = url.split("/");
			baseUrl = "http://" + arr[2];	
		}
		private void findAllVideos(){			
			addVideosFiles(doc.select("meta[property=og:video]"));
			addVideosFlash(doc.select("link[rel=video_src]"), "href");
			addVideosFlash(doc.getElementsByTag("iframe"), "src");
			addVideosYoutube(doc.select("a"));
		}
		private void addVideosFiles(Elements elements){
			for (int i = 0; i < elements.size(); i++) {
				Element el = elements.get(i);
				String url = el.attr("content");
				if(url.endsWith(".mp4") || url.endsWith(".mp3") || url.endsWith(".avi")){
					Video video = new Video(url, VIDEO_TYPE.FILE);
					onProgressUpdate(video);
					videos.add(video);
					videosAmount++;
				}
			}
		}
		private void addVideosFlash(Elements elements,String att){
			for (int i = 0; i < elements.size(); i++) {
				Element el = elements.get(i);
				String url = el.attr(att);
				if(el.hasAttr(att) && !url.isEmpty()){
					Video video;
					if(!url.contains("http://")){
						video = new Video(baseUrl + url, VIDEO_TYPE.FLASH);
					}
					else{
						video = new Video(url, VIDEO_TYPE.FLASH);
					}
					videos.add(video);
					onProgressUpdate(video);
					videosAmount++;
				}
			}
		}
		private void addVideosYoutube(Elements elements){
			for (int i = 0; i < elements.size(); i++) {
				Element el = elements.get(i);
				if(el.hasAttr("href")){
					String url = el.attr("href");
					if(url.contains("youtube")){
						Video video = new Video(url, VIDEO_TYPE.YOUTUBE);
						videos.add(video);
						onProgressUpdate(video);
						videosAmount++;
					}
				}
			}
		}
		public boolean isRunning() {
			return isRunning;
		}

	}

	public interface OnStateChanged{
		void timeLoadStarted();
		void downloadedData(Video video,int downloadNumber,int amount);
		void timeLoadFinished(List<Video> videos);
		void timeLoadCanceled(String message);
	}


	public class Video{
		private String url;
		private VIDEO_TYPE type;

		public Video(String url,VIDEO_TYPE type){
			this.url = url;
			this.type = type;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		public VIDEO_TYPE getVideoType() {
			return type;
		}
		public void setVideoType(VIDEO_TYPE type) {
			this.type = type;
		}
	}
	public enum VIDEO_TYPE{
		FILE,
		FLASH,
		YOUTUBE
	}
}
